package com.mvc4g.example.mockup.client.action;

import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mvc4g.client.ActionInterface;
import com.mvc4g.client.Controller;
import com.mvc4g.example.mockup.client.Constants;
import com.mvc4g.example.mockup.client.MockUpService;
import com.mvc4g.example.mockup.client.MockUpServiceAsync;
import com.mvc4g.example.mockup.client.Session;
import com.mvc4g.example.mockup.client.bean.EmailBean;
import com.mvc4g.example.mockup.client.view.templates.EmailTemplate;
import com.mvc4g.example.mockup.client.view.templates.RootTemplate;
import com.mvc4g.example.mockup.client.view.views.EmailContentView;

public class EmailContentAction implements ActionInterface, Constants {

	private static MockUpServiceAsync services = MockUpService.Util
			.getInstance();

	@SuppressWarnings("unchecked")
	@Override
	public void execute(final Controller controller, Object form) {
		final int index = (Integer) form;

		List<EmailBean> emailList = (List<EmailBean>) Session
				.getAttribute(EMAIL_LIST);
		final EmailBean email = emailList.get(index);
		final boolean displayPrevious = index > 0;
		final boolean displayNext = (index + 1) < emailList.size();
		if (email.getContent() == null) {
			services.getContent(email.getId(), new AsyncCallback<String>(){

				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void onSuccess(String result) {
					email.setContent(result);
					displayContent(controller, email, index, displayPrevious, displayNext);
				}
				
			});

		} else {
			displayContent(controller, email, index, displayPrevious, displayNext);
		}

	}

	private void displayContent(Controller controller, EmailBean email, int index, 
			boolean displayPrevious, boolean displayNext) {
		
		EmailTemplate emailView = (EmailTemplate) controller.getView(EMAIL_TEMPLATE);
		
		RootTemplate rootView = (RootTemplate) controller.getView(ROOT_TEMPLATE);
		rootView.changePage(emailView, null);		
		
		EmailContentView emailContent = (EmailContentView) controller
				.getView(EMAIL_CONTENT_VIEW);
		emailView.changePage(emailContent, GET_EMAIL_CONTENT + "?index=" + index);
		emailContent.displayEmail(email, index, displayPrevious, displayNext);
	}

}
